package com.zhouzi.zhaoyang.ui.activity

import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.view.View.VISIBLE
import android.widget.Toast
import com.google.gson.Gson
import com.neovisionaries.ws.client.WebSocket
import com.neovisionaries.ws.client.WebSocketAdapter
import com.neovisionaries.ws.client.WebSocketException
import com.neovisionaries.ws.client.WebSocketFactory
import com.orhanobut.logger.Logger
import com.zhouzi.zhaoyang.R
import com.zhouzi.zhaoyang.base.App
import com.zhouzi.zhaoyang.base.BaseActivity
import com.zhouzi.zhaoyang.bean.BalancePaymentBean
import com.zhouzi.zhaoyang.bean.CreateQRBean
import com.zhouzi.zhaoyang.bean.GetOrderBean
import com.zhouzi.zhaoyang.bean.OrderDetailBean
import com.zhouzi.zhaoyang.http.HttpConfig
import com.zhouzi.zhaoyang.mvp.p.MorePaymentMethodsActivityPresenter
import com.zhouzi.zhaoyang.mvp.v.IMorePaymentMethodsActivityView
import com.zhouzi.zhaoyang.service.VoiceService
import com.zhouzi.zhaoyang.util.Calculator
import com.zhouzi.zhaoyang.util.EncodingHandler
import com.zhouzi.zhaoyang.util.MyHttp
import com.zhouzi.zhaoyang.util.SizeUtils
import kotlinx.android.synthetic.main.activity_more_payment_methods.*
import kotlinx.android.synthetic.main.activity_pay.tvApShowMoney

class MorePaymentMethodsActivity : BaseActivity(), IMorePaymentMethodsActivityView {
    override fun errorToken() {
        exitToLogin()
    }
    var outTradeNo = ""
    override fun createScanOrderSuccess(createQRBean: CreateQRBean?) {
        val qrBitmap = EncodingHandler.createQRCode(createQRBean?.qrUrl, SizeUtils.dp2px(200f))
        ivApQr.setImageBitmap(qrBitmap)
        outTradeNo = createQRBean!!.outTradeNo
    }

    override fun createScanOrderFailed(msg: String?) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT)
    }

    var p = MorePaymentMethodsActivityPresenter()

    init {
        p.attachView(this)
    }

    override fun getOrderSuccess(orderDetail: OrderDetailBean?) {
        orderDetail?.let {
            App.instance().printProductInformation(orderDetail)
            MyHttp.report(orderDetail)
            finish()

        }

    }


    override fun getOrderFailed(msg: String?) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT)
    }

    override fun showLoadDialog() {
        loadDialog.show()
    }

    override fun dismissLoadDialog() {
        loadDialog.dismiss()
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_more_payment_methods
    }


    var yuan = ""
    var money = 0L
    override fun initView() {

        if ( !TextUtils.isEmpty(intent.getStringExtra("money")) ) {

            yuan = intent.getStringExtra("money")
            money = Calculator.yuan2Fen(yuan)
            tvApShowMoney.text = "原价：" + yuan

        }


        val data = intent.getParcelableExtra<BalancePaymentBean>("data")


        if (data != null) {

            var totalFee = Calculator.fen2Yuan(data.totalFee!!.toLong())
            var memberFee = Calculator.fen2Yuan(data.memberFee!!.toLong())
            tvApShowVipMoney.visibility = VISIBLE
            tvApShowMoney.text = "原价：" + totalFee
            tvApShowVipMoney.text = "会员价：" + memberFee
        }

        var map = mutableMapOf(
            Pair("deviceNo", deviceNo),
            Pair("totalFee", money)
        )
        if (data != null) {
            map.put("memberFee", data.memberFee)
            map.put("phone", data.phone)
            Pair("totalFee", data.totalFee)

        }

        connectSocket(map)

        viewClick()

    }

    private fun viewClick() {
        tvApBtn.setOnClickListener {
            finish()
        }
    }

    private var socket: WebSocket? = null
    var deviceNo = Build.SERIAL
    private fun connectSocket(map: MutableMap<String, Any?>) {
        socket = WebSocketFactory().createSocket(
            HttpConfig.WebSocket_URL + deviceNo,
            10000

        )
        socket?.addListener(object : WebSocketAdapter() {

            override fun onConnected(
                websocket: WebSocket?,
                headers: MutableMap<String, MutableList<String>>?
            ) {
                Handler(Looper.getMainLooper()).post {
                    Logger.d("socket连接成功")
                    /*生成二维码*/
                    p.createScanOrder(map)

                }
            }


            override fun onTextMessage(websocket: WebSocket?, text: String?) {

                Handler(Looper.getMainLooper()).post {

                    val bean = Gson().fromJson(text, GetOrderBean::class.java)

                    Log.e(
                        "webSocket:",
                        text + "\n" + bean.toString() + ":::::" + GetOrderBean(
                            null,
                            null
                        ).toString()
                    )

                    if (outTradeNo == bean.outTradeNo) {
                        if (bean.type == "scan-paying-notice") {
                            if (!loadDialog.isShowing) {
                                loadDialog.setContent("扫码支付中")
                                loadDialog.setCanceledOnTouchOutside(true)
                                loadDialog.show()

                            }
                        } else {
                            if (bean != null && bean.status!!) {
                                val intent = Intent(mContext, VoiceService::class.java)
                                intent.putExtra("voiceStr", "交易成功")
                                startService(intent)
                                // 关闭socket
                                socket?.sendClose()
                                p.getOrder(bean.outTradeNo)
                                var returnMain = Intent(mContext, MainActivity::class.java)
                                startActivity(returnMain)
                                finish()
                                if (loadDialog.isShowing) {
                                    loadDialog.dismiss()
                                }
                            }
                        }
                    }
                }
            }

            override fun onConnectError(websocket: WebSocket?, exception: WebSocketException?) {
                val intent = Intent(mContext, VoiceService::class.java)
                intent.putExtra("voiceStr", "服务器连接失败，请使用刷脸支付")
                startService(intent)
            }
        })
        socket?.connectAsynchronously()
    }


    override fun onDestroy() {
        super.onDestroy()
        socket?.sendClose()
        p.detachView()


    }


}
